#include "player.h"
#include "BLE.h"

extern int com;
PLAYER::PLAYER(MUSIC *m_ptr): m_p(m_ptr)
{
  m_rhythm = 1;     //播放速度设置为1;
  breakpoint = 0;   //断点清零
  playing = 1;
  IsPlay = false;
  IsDisplay = false;
  mode = SEQUENCE;
  BLE_send("播放模式:顺序循环");
}
void PLAYER::play()
{
  int i = breakpoint;
  BLE_send((m_p + playing - 1)->name);
  if (IsPlay == true)
  {
    for ( i = breakpoint; i < (m_p + playing - 1)->MucLength; i++)
    {
      if ( (m_p + playing - 1)->notes[i] != 0)
        tone(port, (m_p + playing - 1)->notes[i]); //将notes中的数字依次执行出来
      display(map((m_p + playing - 1)->notes[i], 200, 1500, 0, 7));
      delay((m_p + playing - 1)->beats[i] / m_rhythm); //将beats中的数字依次执行出来
      noTone(port); //在音符之间设置一个间隔，避免连音
      delay(10);
      ComAnalysis();
      if (com == 1)
      {
        IsPlay = !IsPlay;
        breakpoint = i;
        break;
      }
      else if (com == 2)
      {
        next();
        break;
      }
      else if (com == 3)
      {
        changeMode();
      }
    }
  }
  if (i >= (m_p + playing - 1)->MucLength)
  {
    next();
  }
}
void PLAYER::p_stop()
{

}
void PLAYER::next()
{
  if (mode == SEQUENCE)
  {
    playing++;
    if (playing >= 5 )
      playing = 1;
  }
  else if (mode == CIRCULATION)
  {

  }
  else
  {
    unsigned long currentTime = millis();
    playing = currentTime % 5;
  }
  breakpoint = 0;
  delay(200);
}
void PLAYER::changeMode()
{
  switch (mode)
  {
    case SEQUENCE: mode = CIRCULATION; BLE_send("模式:单曲循环"); break;
    case CIRCULATION: mode = RANDOM; BLE_send("模式:随机循环"); break;
    case RANDOM: mode = SEQUENCE; BLE_send("模式:顺序循环"); break;
    default: break;
  }
}

